package com.fenghongzhang.lib_core.base

import android.content.Context
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import com.alibaba.android.arouter.launcher.ARouter
import com.fenghongzhang.lib_core.R
import com.fenghongzhang.lib_core.state.Failed
import com.fenghongzhang.lib_core.state.Loading
import com.fenghongzhang.lib_core.state.RequestEvent
import com.fenghongzhang.lib_core.state.Success
import com.fenghongzhang.lib_core.utils.ToastUtils
import com.google.android.material.snackbar.Snackbar
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.flow.SharedFlow

abstract class BaseActivity<VM : BaseViewModel, VDB : ViewDataBinding> : AppCompatActivity() {
    open val mPageCanBack: Boolean = true
    abstract val mViewModel: VM
    protected lateinit var mBinding: VDB
    abstract val mLayoutResId: Int
    //loadingView
    protected var mLoadingView: View? = null
    //rootView
    protected lateinit var mRootView: ViewGroup
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //ARouter 传值自动注入
        ARouter.getInstance().inject(this)
        mBinding = DataBindingUtil.setContentView(this, mLayoutResId)
        mBinding.lifecycleOwner = this
        initGlobalView()
        initView()
        initStatusBar()
        initListener()
        initData()
    }
    open fun initView() {
    }
    //初始化状态栏
    protected open fun initStatusBar() {
        ImmersionBar.with(this).init()
    }

    abstract fun initListener()

    abstract fun initData()

    private fun initGlobalView() {
        mRootView = window.decorView as ViewGroup
        initLoadingView()
    }

    private fun initLoadingView() {
        if (mLoadingView == null) {
//            mLoadingView = layoutInflater.inflate(R.layout.dialog_common_progress, mRootView, false)
//            mLoadingView!!.setOnClickListener(View.OnClickListener { v: View? -> })
//            setLoadingViewVisible(false)
//            mRootView.addView(mLoadingView)
        }
    }

    open fun setLoadingViewVisible(show: Boolean, msg: String = "") {
        mLoadingView?.let {
            val textView = it.findViewById<TextView>(R.id.tv_text)
            if (show && msg.isNotEmpty())
                textView.text = msg
            if (show) it.visibility = View.VISIBLE else it.visibility = View.GONE
        }
    }
    open fun showToast(stringRes: String) {
        Snackbar.make(window.decorView, stringRes, Snackbar.LENGTH_LONG).show()
    }

    open fun showToast(view: View?, stringRes: Int) {
        Snackbar.make(view ?: window.decorView, stringRes, Snackbar.LENGTH_LONG).show()
    }

    fun dismissKeyboard() {
        try {
            val view = window.peekDecorView()
            if (view != null) {
                val im = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                im.hideSoftInputFromWindow(view.windowToken, 0)
            }
        } catch (e: Exception) {
        }
    }

    fun hideKeyboard(view: View) {
        (view.context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?)?.hideSoftInputFromWindow(view.windowToken, 0)
    }
    fun showSoftKeyBoard(view: View) {
        view.requestFocus()
        view.postDelayed({
            val imm = view.context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
        }, 200)

    }
    private var lastPressBack = 0L
    private fun isPressBackToExitApp(timeStamp: Long): Boolean {
        if (lastPressBack == timeStamp)
            return false
        //小于3s，退出
        return if (timeStamp - lastPressBack < 2_000) {
            true
        } else {
            ToastUtils.showShort(this, "再按一次退出软件")
            lastPressBack = timeStamp
            false
        }
    }

    // 添加通用的状态监听，这里只做Loading的隐藏，显示和错误消息Toast
    open fun addCommonStateListener(stateListener: SharedFlow<RequestEvent>) {
        stateListener.observeWithLifecycle(this, Lifecycle.State.STARTED) {
            when (it) {
                is Success -> {
                    setLoadingViewVisible(false)
                }
                is Loading -> {
                    setLoadingViewVisible(true)
                }
                is Failed -> {
                    // 商品已下架 不Toast
                    if (it.message != "商品已下架") {
                        ToastUtils.showShort(this, it.message)
                    }
                    setLoadingViewVisible(false)
                    onLoadFailed(it.message)
                }
                else -> {}
            }
        }
    }
    open fun onLoadFailed(msg: String) {}

//    override fun onBackPressed() {
//        val timeStamp = System.currentTimeMillis()
//        //activity可返回
//        if (mPageCanBack) {
//            Log.d("pressBack", "activity :${this} -- ${mPageCanBack}")
//            super.onBackPressed()
//            return
//        }
//
//        val fragments = supportFragmentManager.fragments.filterIsInstance<BaseFragment<*, *>>()
//
//        //无fragment，处理退出
//        if (fragments.isEmpty() && isPressBackToExitApp(timeStamp)) {
//            MobclickAgent.onKillProcess(appContext)
//            super.onBackPressed()
//            return
//        }
//        //activity带有fragment
//        for (fragment in fragments) {
//            Log.d("pressBack", "fragment ${fragment} -- ${fragment.isVisible} -- ${fragment.mPageCanBack}")
//            if (fragment.isVisible) {
//                //可返回
//                if (fragment.mCanBack) {
//                    super.onBackPressed()
//                    break
//                } else {
//                    //不可返回，处理退出
//                    if (isPressBackToExitApp(timeStamp)) {
//                        MobclickAgent.onKillProcess(appContext)
//                        super.onBackPressed()
//                        break
//                    }
//                }
//            }
//
//        }
//    }

}